package com.hwq.sql.tool.utils;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.math.BigDecimal;

public class ExcelUtil {

    /**
     * 读取 单元格的值，并同一转化为字符串
     * @param cell 单元格
     */
    public static String getCellValue(XSSFCell cell, int sacle) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.BOOLEAN) {
            boolean value = cell.getBooleanCellValue();
            return value ? "TRUE" : "FALSE";
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            double value = cell.getNumericCellValue();
            return simplifyNumber(value, sacle);
        }
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        }
        if (cell.getCellType() == CellType.FORMULA) {
            if (cell.getCachedFormulaResultType() == CellType.NUMERIC) {
                double value = cell.getNumericCellValue();
                return simplifyNumber(value, sacle);
            } else {
                return cell.getStringCellValue();
            }
        }
        return null;
    }
    /**
     * 读取 单元格的值，并同一转化为字符串
     * @param cell 单元格
     */
    public static String getCellValue(XSSFCell cell) {
        return getCellValue(cell, 0);
    }


    /**
     * 数字简化为字符串
     * @param num 双精度的数字
     */
    public static String simplifyNumber(Double num, int scale) {
        BigDecimal decimal = new BigDecimal(num);
        decimal.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return decimal.toString();
    }

}
